package jeff.plugin.mybatis.code;

import java.io.File;
import java.io.FileInputStream;

import jeff.plugin.mybatis.code.visitor.MergeUtil;
import jeff.plugin.mybatis.lang.Charsets;
import jeff.plugin.mybatis.util.IOUtil;
import jeff.plugin.mybatis.util.StringUtil;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MyDefaultShellCallback extends DefaultShellCallback {

	public MyDefaultShellCallback() {
		super(true);
	}

    @Override
	public boolean isMergeSupported() {
		return true;
	}

	@Override
	public String mergeJavaFile(String newFileSource, File existingFile, String[] javadocTags, String fileEncoding) {
		if(existingFile == null || existingFile.getName().endsWith("Example.java")){
			return newFileSource;
		}
		try {
			byte[] bytes = IOUtil.readBytes(new FileInputStream(existingFile));
			String oldSource = StringUtil.str(bytes, Charsets.toCharset(fileEncoding));

			return MergeUtil.merge(oldSource, newFileSource);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newFileSource;
	}

}